//
//  SMInfiniteCarouselView.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/13.
//

import SwiftUI

import SwiftUI

struct SMInfiniteCarouselView<Data: RandomAccessCollection, Content: View>: View where Data.Element: Identifiable & Hashable {
    let data: Data
    let autoScrollInterval: TimeInterval?
    let showsIndicators: Bool
    let content: (Data.Element) -> Content
    let onItemTapped: ((Data.Element) -> Void)?
    
    @State private var currentIndex = 0
    @State private var timer: Timer?
    
    init(_ data: Data,
         autoScrollInterval: TimeInterval? = 3.0,
         showsIndicators: Bool = true,
         @ViewBuilder content: @escaping (Data.Element) -> Content,
         onItemTapped: ((Data.Element) -> Void)? = nil) {
        self.data = data
        self.autoScrollInterval = autoScrollInterval
        self.showsIndicators = showsIndicators
        self.content = content
        self.onItemTapped = onItemTapped
    }
    
    var body: some View {
        GeometryReader { geometry in
            TabView(selection: $currentIndex) {
                ForEach(Array(data.enumerated()), id: \.element.id) { index, item in
                    content(item)
                        .frame(width: geometry.size.width, height: geometry.size.height)
                        .tag(index)
                        .onTapGesture {
                            onItemTapped?(item)
                        }
                }
            }
            .tabViewStyle(.page(indexDisplayMode: showsIndicators ? .automatic : .never))
            .onAppear {
                setupAutoScroll()
            }
            .onDisappear {
                timer?.invalidate()
            }
        }
    }
    
    private func setupAutoScroll() {
        guard let interval = autoScrollInterval, interval > 0, data.count > 1 else { return }
        
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in
            withAnimation {
                currentIndex = (currentIndex + 1) % data.count
            }
        }
    }
}
